package com.pinxixi.order.controller;

import com.alibaba.fastjson.JSON;
import com.pinxixi.api.order.OrderControllerApi;
import com.pinxixi.framework.domain.cart.ItemCart;
import com.pinxixi.framework.domain.order.OrderEntity;
import com.pinxixi.framework.model.response.CommonCode;
import com.pinxixi.framework.model.response.ListResponseResult;
import com.pinxixi.framework.model.response.QueryResponseResult;
import com.pinxixi.framework.model.response.QueryResult;
import com.pinxixi.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController  //@ResponseBody+@Controller
@RequestMapping("/order")
@CrossOrigin(origins = "*")
public class OrderController implements OrderControllerApi {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @PostMapping("createPreOrder")
    public QueryResponseResult createPreOrder(@RequestBody List<ItemCart> list) {
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForList().leftPushAll(key,list);
        //redisTemplate.boundListOps(key).leftPushAll(list);
        redisTemplate.boundListOps(key).expire(1, TimeUnit.MINUTES);
        return new QueryResponseResult(CommonCode.SUCCESS,key);
    }

    @Override
    @GetMapping("/getPreOrder/{id}")
    public ListResponseResult getPreOrder(@PathVariable("id") String id) {
        List<ItemCart> list = redisTemplate.opsForList().range(id, 0, -1);
        QueryResult<ItemCart> queryResult = new QueryResult<>();
        queryResult.setList(list);
        return new ListResponseResult(CommonCode.SUCCESS,queryResult);
    }

    @Override
    @PostMapping("createOrder")
    public QueryResponseResult createPreOrder(@RequestBody OrderEntity orderEntity, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        //获取用户ID
        Jwt decode = JwtHelper.decode(token);
        String claims = decode.getClaims();
        Map map = JSON.parseObject(claims, Map.class);
        String id = (String) map.get("id");

        orderEntity.getOrderInfo().setUserId(Long.parseLong(id));

        return orderService.createOrder(orderEntity);
    }

    @Override
    @GetMapping("/getOrder/{id}")
    public QueryResponseResult getOrder(@PathVariable("id") String id) {
        return orderService.getOrder(id);
    }

}
